package com.dianxin.farm.api;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dianxin.farm.entity.GoodsInfo;
import com.dianxin.farm.entity.OrderBill;
import com.dianxin.farm.entity.pojo.OrderDetailPojo;
import com.dianxin.farm.entity.pojo.OrderPojo;
import com.dianxin.farm.filter.AuthorCheck;
import com.dianxin.farm.mapper.goods.GoodsInfoImageMapper;
import com.dianxin.farm.mapper.goods.GoodsInfoMapper;
import com.dianxin.farm.mapper.bill.OrderBillMapper;
import com.dianxin.farm.request.common.IdRequest;
import com.dianxin.farm.request.order.CreateOrderRequest;
import com.dianxin.farm.request.order.OrderRequest;
import com.dianxin.farm.service.CurrentLoginService;
import com.dianxin.farm.util.exception.UserOperationException;
import com.dianxin.farm.util.order.Generator;
import com.dianxin.farm.util.order.IdGeneratorFactory;
import com.dianxin.farm.util.util.Assert;
import com.dianxin.farm.util.util.StringUtil;
import com.dianxin.farm.util.web.ApiResponse;
import com.dianxin.farm.util.web.ApiResponseUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 商品服务订单表 前端控制器
 * </p>
 *
 * @author xukai
 * @since 2020-09-14
 */
@RestController
@RequestMapping(value = "/orderBill", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@Api(description = "订单接口")
public class OrderBillController {
    @Resource
    private OrderBillMapper orderBillMapper;
    @Resource
    private CurrentLoginService currentLoginService;

    @Resource
    private GoodsInfoMapper goodsInfoMapper;
    @Resource
    private GoodsInfoImageMapper goodsImageMapper;

    private static final Generator generator = IdGeneratorFactory.create("order_bill");


    @RequestMapping(value = "/myOrders")
    @ResponseBody
    @AuthorCheck()
    @ApiOperation("我的订单列表")
    public ApiResponse<PageInfo<OrderPojo>> ordersPage(@Valid @RequestBody OrderRequest request) {
        Integer creatorId = currentLoginService.getId();
        PageHelper.startPage(request.getPage(), request.getSize());
        String orderNo = StringUtil.nullOrNotBlank(request.getOrderNo());
        String goodsName = StringUtil.nullOrNotBlank(request.getGoodsName());
        Integer status = request.getStatus();
        if (status != null && status == -1) {
            status = null;
        }
        List<OrderPojo> list = orderBillMapper.selectCondition(orderNo, request.getStartTime(), request.getEndTime(), goodsName, request.getPayType(), status, creatorId);


        return ApiResponseUtils.success(new PageInfo<>(list));
    }


    @RequestMapping(value = "/orderDetails")
    @ResponseBody
    @AuthorCheck()
    @ApiOperation("查看订单列表的详情,传入订单的id")
    public ApiResponse<List<OrderDetailPojo>> ordersPage(@Valid @RequestBody IdRequest request) {
        Integer billId = request.getId();
        Assert.notNull(billId, "请正确选择订单号");
        OrderBill orderBill = orderBillMapper.selectById(billId);
        if (orderBill == null) {
            throw new UserOperationException("订单不存在");
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("order_id", billId);

        return ApiResponseUtils.success();
    }


    @RequestMapping(value = "/createBill")
    @ResponseBody
    @AuthorCheck()
    @ApiOperation("提交订单，返回订单的id")
    @Transactional
    public ApiResponse<Map<String, String>> payBill(@Valid @RequestBody CreateOrderRequest request) {
        Integer customerId = currentLoginService.getId();
        LocalDateTime now = LocalDateTime.now();
        String orderNo = String.valueOf(generator.generate());
        //订单价格
        OrderBill bill = new OrderBill();
        bill.setCreateTime(now);
        bill.setOrderNo(orderNo);
        bill.setStatus(0);
        bill.setCustomerId(customerId);

        Integer orderBillId = bill.getId();
        BigDecimal price = new BigDecimal("0");

        Integer goodsInfoId = request.getGoodsInfoId();
        Integer buyNum = request.getGoodsNum();
        if (buyNum != 1) {
            throw new UserOperationException("正确填写购买数量" + goodsInfoId);
        }

        GoodsInfo goodsInfo = goodsInfoMapper.selectById(goodsInfoId);
        if (goodsInfo == null || goodsInfo.getShelfStatus() == 0) {
            throw new UserOperationException("商品状态异常" + goodsInfoId);
        }

        BigDecimal goodsPrice = goodsInfo.getPrice();
        //商品价格
        BigDecimal singlePrice = goodsPrice.multiply(new BigDecimal(buyNum));
        price = price.add(singlePrice);
        if (price.compareTo(new BigDecimal("0")) ==-1) {
            throw new UserOperationException("异常订单，请检查订单价格");
        }

        bill.setGoodsInfoId(goodsInfoId);
        bill.setOrderPrice(price);
        orderBillMapper.insert(bill);
        Map<String, String> map = new HashMap<>();
        map.put("order_bill_id", orderBillId.toString());

        return ApiResponseUtils.success(map);

    }

}
